package com.project.zsxd.server.upload.controller;

import com.project.zsxd.server.common.bean.Result;
import com.project.zsxd.server.common.enums.UploadTypeEnum;
import com.project.zsxd.server.common.exception.SystemException;
import com.project.zsxd.server.common.helper.FileHelper;
import com.project.zsxd.server.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import static com.project.zsxd.server.common.enums.ResultEnum.FILE_UPLOAD_ERROR;

@RestController
@Slf4j
@RequestMapping("/upload")
public class UploadController {

    /**
     * 上传图片文件
     * @param imgFile 图片文件
     * @return 文件访问路径
     * @throws IOException 上传异常
     */
    @RequestMapping("/img")
    public Result uploadImg(@RequestParam("imgFile") MultipartFile imgFile) throws IOException {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (Objects.isNull(imgFile.getOriginalFilename()) || !FileHelper.isImg(imgFile.getOriginalFilename())) {
            log.error("imgFile is null or not img");
            throw new SystemException(FILE_UPLOAD_ERROR);
        }
        String suffix = imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf("."));
        File headFile = new File(FileHelper.getUploadPath(UploadTypeEnum.HeadIcon, suffix));
        if (!headFile.getParentFile().exists() && !headFile.getParentFile().mkdirs()) {
            log.error("headFile save dir[{}] create failed.", headFile.getParentFile().getAbsolutePath());
        }
        imgFile.transferTo(headFile);
        String downloadUrl = FileHelper.getRelativeDownloadUrl(UploadTypeEnum.HeadIcon, headFile.getName());
        log.info("uploadImg user:{}, img:{}", user.getUserName(), downloadUrl);
        return Result.success(downloadUrl);
    }
}
